package com.jackchong.net

import com.jackchong.utils.JLog
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.count
import kotlin.collections.set

/**
 * author : chong.huang
 * e-mail : chong.huang@ecarx.com.cn
 * create : 4/23/21
 * desc   :
 */
object NetCache {

    private val netArray = ArrayList<NetCacheData>(100)
    private val netMap = HashMap<Int, String>(100)

    fun put(hashCode: Int, url: String) {
        netArray.add(NetCacheData(hashCode, url))
        netMap[hashCode] = url
    }

    fun contain(hashCode: Int): Boolean {
        val url = netMap[hashCode]
        return (url != null && netArray.count { it.url == url } > 1).apply {
            if (this) {
                JLog.i("jhttp", "$url 的接口已存在")
            }
        }
    }

    fun getUrl(hashCode: Int): String? = netMap[hashCode]

    fun remove(hashCode: Int) {
        val index = netArray.indexOfFirst { it.hashCode == hashCode }
        if (index != -1){
            netArray.removeAt(index)
        }
        netMap.remove(hashCode)
    }

    data class NetCacheData(val hashCode: Int, val url: String)
}
